package com.papper.mng.controller.sys;

import com.google.common.collect.Lists;
import com.papper.common.bean.sys.SysCode;
import com.papper.common.bean.sys.SysConfig;
import com.papper.common.config.PapperStorage;
import com.papper.common.enums.DataStatusEnum;
import com.papper.common.exception.ServiceException;
import com.papper.common.mq.redis.RedisCacheMqService;
import com.papper.common.service.sys.SysConfigService;
import com.papper.common.utils.tool.StringTool;
import com.papper.mng.controller.BaseAction;
import com.papper.mng.domain.DwzResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/sys/config")
public class SysConfigController extends BaseAction {
    @Autowired
    SysConfigService    sysConfigService;
    @Autowired
    RedisCacheMqService redisCacheMqService;

    /**
     * 系统配置
     *
     * @return
     */
    @GetMapping(value = "")
    public String execute(Model model, Long pid, String sv) {
        // 顶级字典
        Example          example  = new Example(SysCode.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("parentId", 0);
        if (!StringTool.isEmpty(sv)) {
            criteria.andLike("codeKey", "%" + StringTool.nullToEmpty(sv) + "%");
        }
        example.setOrderByClause("code_sort asc");
        model.addAttribute("sv", StringTool.nullToEmpty(sv));
        List<SysConfig> codes  = sysConfigService.find(example);
        SysConfig       parent = sysConfigService.findById(pid);
        if (codes == null || codes.isEmpty()) {
            return render("sys/config/index");
        }
        if (parent == null) {
            parent = codes.get(0);
        } else if (parent != null && parent.getParentId().intValue() != 0) {
            parent = codes.get(0);
        } else {
            boolean isHas = false;
            for (SysConfig code : codes) {
                if (code.getId().equals(parent.getId())) {
                    isHas = true;
                    break;
                }
            }
            if (!isHas) {
                parent = codes.get(0);
            }
        }
        model.addAttribute("codes", codes);
        model.addAttribute("parent", parent);
        model.addAttribute("pid", parent.getId());
        // 字典配置信息
        List<SysConfig> childCodes = sysConfigService.findByParentId(parent.getId());
        model.addAttribute("childCodes", childCodes);
        return render("sys/config/index");
    }

    /**
     * 系统配置
     *
     * @return
     */
    @RequestMapping(value = "/child")
    public String child(Model model, Long pid) {
        SysConfig parent = sysConfigService.findById(pid);
        model.addAttribute("parent", parent);
        List<SysConfig> codes = sysConfigService.findByParentId(pid);
        model.addAttribute("codes", codes);
        return render("sys/config/child");
    }

    /**
     * 系统配置_新增
     *
     * @param pid
     * @
     */
    @GetMapping(value = "/add")
    public String add_get(Model model, Long pid) {
        model.addAttribute("nick", getNick());
        if (pid == 0) {
            model.addAttribute("pid", pid);
            model.addAttribute("pname", "顶级配置");
        } else {
            SysConfig parent = sysConfigService.findById(pid);
            model.addAttribute("pid", pid);
            model.addAttribute("pname", parent.getCodeKey());
        }
        return render("sys/config/add");
    }

    @PostMapping(value = "/add")
    @ResponseBody
    public DwzResponse add_post(HttpServletRequest _request, SysConfig sysConfig) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        if (sysConfig == null) {
            return new DwzResponse("300", "参数[SysConfig]异常！");
        }
        SysConfig dbCode = sysConfigService.findByKey(sysConfig.getCodeKey(), sysConfig.getParentId().longValue());
        if (dbCode != null) {
            return new DwzResponse("300", "该值已存在！");
        }
        try {
            sysConfig.setDataStatus(DataStatusEnum.OPEN.getCode());
            sysConfig.setCreateTime(new Date());
            sysConfig.setModifyTime(new Date());
            sysConfigService.save(sysConfig);
            return new DwzResponse("200", "系统配置添加成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统配置添加失败:" + e.getMessage() + "!!!");
        }
    }

    /**
     * 系统配置_更新
     *
     * @param _response
     * @param id
     * @
     */
    @GetMapping(value = "/edit")
    public String edti_get(HttpServletResponse _response, Model model, Long id) {
        SysConfig entity = sysConfigService.findById(id);
        model.addAttribute("entity", entity);
        model.addAttribute("nick", getNick());
        return render("sys/config/edit");
    }

    @PostMapping(value = "/edit")
    @ResponseBody
    public DwzResponse edit_post(HttpServletRequest _request, SysConfig sysConfig) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        if (sysConfig == null || sysConfig.getId() == null) {
            return new DwzResponse("300", "参数[SysConfig]异常！");
        }
        try {
            sysConfig.setModifyTime(new Date());
            sysConfigService.update(sysConfig);
            return new DwzResponse("200", "系统配置修改成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统配置修改失败:" + e.getMessage());
        }
    }

    /**
     * 系统配置_删除
     *
     * @param id
     * @
     */
    @PostMapping(value = "/del")
    @ResponseBody
    public DwzResponse del_post(HttpServletRequest _request, Long id) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        if (id == null || id.intValue() <= 0) {
            return new DwzResponse("300", "参数[id]异常！");
        }
        try {
            sysConfigService.deleteById(id);
            return new DwzResponse("200", "系统配置删除成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统配置修改失败:" + e.getMessage());
        }
    }

    /**
     * 系统配置_详情
     *
     * @return
     */
    @GetMapping(value = "/detail")
    public String detail(HttpServletResponse _response, Model model, Long id) {
        SysConfig sysConfig = sysConfigService.findById(id);
        model.addAttribute("entity", sysConfig);
        return render("sys/config/detail");
    }

    /**
     * 系统配置_刷新缓存
     */
    @PostMapping(value = "/flush")
    @ResponseBody
    public DwzResponse flush_post(HttpServletRequest _request) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        PapperStorage.initStorage(Lists.newArrayList("Local", "Config", "System"));
        redisCacheMqService.producerEvent("MqConfigFlush", "Local,Config,System");
        return new DwzResponse("200", "系统配置刷新成功!!!");
    }
}
